package com.bk.dao;

import com.bk.model.User;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Ayi
 */
// 登录与注册，数据库操作类
public class LoginAndRegisterDao {
    // 登录的数据库操作
    public User login(Connection connection, User tempUser) throws SQLException {
        // 登录查询的SQL语句
        String sqlLOGIN = "select * from user where uname=? and upassword=?";
        // 创建基于此语句的预处理对象
        PreparedStatement ps = connection.prepareStatement(sqlLOGIN);
        // 设置 ？ 处的具体值
        ps.setString(1, tempUser.getUname());
        ps.setString(2, tempUser.getUpassword());
        // 获取结果集
        ResultSet rs = ps.executeQuery();
        // 成功返回用户对象
        if (rs.next()) {
            User resUser = new User(rs.getString("uname"));
            resUser.setUid(rs.getString("uid"));
            resUser.setUpassword(rs.getString("upassword"));
            resUser.setUcredit(rs.getString("ucredit"));
            resUser.setIsAdmin(rs.getString("isAdmin"));
            return resUser;
        }
        // 失败返回null
        return null;
    }

    // 注册的数据库操作
    public boolean reg(Connection connection, User tempUser) throws SQLException {
        // 注册的SQL语句
        String sqlREG = "insert into user values (null, ?, ?, 0, '良好', ?)";
        // 创建基于此语句的预处理对象
        PreparedStatement ps = connection.prepareStatement(sqlREG);
        // 设置 ？ 处的具体值
        ps.setString(1, tempUser.getUname());
        ps.setString(2, tempUser.getUpassword());
        ps.setString(3, tempUser.getIsAdmin());
        // 获取结果集
        try {
            ps.executeUpdate();
            return true;
        }catch (MySQLIntegrityConstraintViolationException e){
            return false;
        }
    }
}
